package com.xiaoq.logs.endpoint;

import com.xiaoq.BaseEndpoint2B;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.logs.entity.NginxLog;
import com.xiaoq.logs.service.NginxLogService;
import com.xiaoq.logs.vo.NginxLogStatisVo;
import com.xiaoq.logs.vo.NginxLogVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenjh on 2018/2/11.
 */
@RestController
@RequestMapping(value = "/api/v1/log")
public class NginxLogEndPoint extends BaseEndpoint2B{

    private static final class NginxLogVoResponse extends GenericDataResponse<NginxLogVo> {};
    private static final class NginxLogStatisResponse extends GenericDataResponse<NginxLogStatisVo> {};

    @Autowired
    private NginxLogService nginxLogService;


    @ApiOperation(value="nginx 日志", notes="nginx 日志")
    @ApiResponses({
            @ApiResponse(code = 200, response = NginxLogVoResponse.class, message = "nginx 日志")
    })
    @GetMapping(value = "", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> logs(@RequestParam(value = "shopId", defaultValue = "") @ApiParam(value="shopId", required=false) String shopId) {

        if(StringUtils.isEmpty(shopId)){
            shopId = getShopId();
        }

        List<NginxLog> nginxLogList = nginxLogService.findNginxLogList(shopId, System.currentTimeMillis(), null);

        List<NginxLogVo> nginxLogVoList = new ArrayList<>();
        NginxLogVo nginxLogVo;
        if(CollectionUtils.isNotEmpty(nginxLogList)){
            for(NginxLog nginxLog : nginxLogList){
                nginxLogVo = new NginxLogVo();
                BeanUtils.copyProperties(nginxLog, nginxLogVo);
                nginxLogVoList.add(nginxLogVo);
            }
        }

        return NginxLogVoResponse.okWithData(nginxLogVoList);
    }


    @ApiOperation(value="日志浏览量统计", notes="日志浏览量统计")
    @ApiResponses({
            @ApiResponse(code = 200, response = NginxLogStatisResponse.class, message = "日志浏览量统计")
    })
    @GetMapping(value = "/statis", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> count(@RequestParam(value = "shopId", defaultValue = "") @ApiParam(value="shopId", required=false) String shopId) {

        if(StringUtils.isEmpty(shopId)){
            shopId = getShopId();
        }

        DateTime currentDate = new DateTime();
        DateTime yestodayEnd = new DateTime(currentDate.getYear(),
                currentDate.getMonthOfYear(),
                currentDate.getDayOfMonth(),
                0,
                0);
        DateTime yestodayBegin = yestodayEnd.minusDays(1);

        long todayCount = nginxLogService.findNginxLogCount(shopId, currentDate.getMillis(), yestodayEnd.getMillis());
        long yestodayCount = nginxLogService.findNginxLogCount(shopId, yestodayEnd.getMillis(), yestodayBegin.getMillis());

        long todayUvCount = nginxLogService.findNginxLogCountUv(shopId, currentDate.getMillis(), yestodayEnd.getMillis());
        long yestodayUvCount = nginxLogService.findNginxLogCountUv(shopId, yestodayEnd.getMillis(), yestodayBegin.getMillis());

        NginxLogStatisVo nginxLogStatis = new NginxLogStatisVo();
        nginxLogStatis.setTodayViewCount(todayCount);
        nginxLogStatis.setYesterdayViewCount(yestodayCount);
        nginxLogStatis.setTodayViewPageCount(todayUvCount);
        nginxLogStatis.setYesterdayViewPageCount(yestodayUvCount);
        return NginxLogStatisResponse.okWithData(nginxLogStatis);
    }

    @ApiOperation(value="nginx日志查询", notes="nginx日志查询")
    @ApiResponses({
            @ApiResponse(code = 200, response = NginxLogVoResponse.class, message = "nginx日志查询")
    })
    @GetMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> list(@RequestParam(value = "shopId", defaultValue = "")
                                      @ApiParam(value="shopId", required=false) String shopId,
                                  @RequestParam(value = "requestUrl", defaultValue = "")
                                      @ApiParam(value="requestUrl", required=false) String requestUrl,
                                  @RequestParam(value = "minRequestTime", defaultValue = "")
                                      @ApiParam(value="minRequestTime", required=false) Double minRequestTime,
                                  @ApiParam(required = false, name = "beginMillis", value = "开始时间(yyyy-MM-dd HH:mm:ss)")
                                  @RequestParam(required = false)  String beginMillis,
                                  @ApiParam(required = false, name = "endMillis", value = "结束时间 (yyyy-MM-dd HH:mm:ss)")
                                      @RequestParam(required = false)  String endMillis) {

        if(StringUtils.isEmpty(shopId)){
            shopId = getShopId();
        }

        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        Long beginMillisLong = null;
        Long endMillisLong = null;
        if(StringUtils.isNotBlank(beginMillis)){
            try {
                beginMillisLong = DateTime.parse(beginMillis, format).getMillis();
            }catch (Exception e){
                return GenericResponse.ng("开始时间格式不对");
            }
        }
        if(StringUtils.isNotBlank(endMillis)){
            try {
                endMillisLong = DateTime.parse(endMillis, format).getMillis();
            }catch (Exception e){
                return GenericResponse.ng("结束时间格式不对");
            }
        }

        List<NginxLog> nginxLogList = nginxLogService.findNginxLogList(shopId, requestUrl, minRequestTime,beginMillisLong, endMillisLong);

        List<NginxLogVo> nginxLogVoList = new ArrayList<>();
        NginxLogVo nginxLogVo;
        if(CollectionUtils.isNotEmpty(nginxLogList)){
            for(NginxLog nginxLog : nginxLogList){
                nginxLogVo = new NginxLogVo();
                BeanUtils.copyProperties(nginxLog, nginxLogVo);
                nginxLogVoList.add(nginxLogVo);
            }
        }

        return NginxLogVoResponse.okWithData(nginxLogVoList);
    }

}
